﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Windows.Forms;
using System.IO;
using System.Reflection;

namespace DynamicObject_t.Options
{
    public class Helper
    {        

        public static List<EntityLayer.IClassEntity> GetEntities(out bool IsError)
        {
            List<EntityLayer.IClassEntity> list = new List<EntityLayer.IClassEntity>();
            IsError = false;
            try
            {
                XElement root = XElement.Load(Properties.Settings.Default.OptionFile);
                
                    var Ents = root.Elements();
                    foreach (var h in Ents)
                    {
                        list.Add(GetEntity(h.Attribute(XName.Get("class")).Value, h.Attribute(XName.Get("path")).Value));
                    }
                
            }
            catch (Exception ex)
            {
                Log.WriteErrorLine(ex.ToString());
                IsError = true;
            }
            return list;
        }

        static EntityLayer.IClassEntity GetEntity(string ClassName, string AssemblyFile)
        {
            if (!File.Exists(AssemblyFile)) throw new FileNotFoundException("Can't find assembly file.");

            Assembly assembly = Assembly.LoadFile(Application.StartupPath + "\\" + AssemblyFile);

            return (EntityLayer.IClassEntity)Activator.CreateInstance(assembly.GetType(ClassName));
        }
    }
}
